//
//  CheckBarcodeDetailViewController.m
//  
//
//  Created by 李飞 on 15/11/16.
//
//

#import "CheckBarcodeDetailViewController.h"
#import "DetailsTableViewCell.h"
#import "UserBSGetBarcodeDatail.h"
#import "MJRefresh.h"
#import "BarcodeDetail.h"

#define ROW_HEIGHT                180

@interface CheckBarcodeDetailViewController ()
{
    int _refreshPage;
    BOOL isHedaRefresh;
    NSNumber* _allPay;
    NSNumber* _monthPay;
    bool  _isSucess;
}


@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation CheckBarcodeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"核销记录";
    //    //添加上提下拉加载刷新
        [self addheaderRefresh];
        [self addfooterRefresh];
    _refreshPage = 1;
    _allPay = 0;
    _monthPay = 0;
    isHedaRefresh = NO;
    
    self.dataArray = [NSMutableArray array];
    
    //服务器获取信息
    UserBSGetBarcodeDatail *userBSGetBarcodeDatail = [[UserBSGetBarcodeDatail alloc] init];
    userBSGetBarcodeDatail.page = [NSString stringWithFormat:@"%d",_refreshPage];
    [self showProgressView];
    [self runService:userBSGetBarcodeDatail andComplete:^(EACService *service) {
        [self hideProgressView];
    } andSuccess:^(EACService *service, id o) {
        UserBSGetBarcodeDatailResult *userBSGetBarcodeDatailResult = o;
        if (userBSGetBarcodeDatailResult.isSucess)
        {
            //初始化界面
            _allPay = userBSGetBarcodeDatailResult.allpay;
            _monthPay = userBSGetBarcodeDatailResult.monthpay;
            NSArray* detailsArray = userBSGetBarcodeDatailResult.data;
            [  detailsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                BarcodeDetail *details = [[BarcodeDetail alloc] initWithclassName:obj[@"ticket_name"] classNum:obj[@"student_name"] andclassTime:obj[@"time"]];
                [self.dataArray addObject:details];
                
            } ];
            
            //主线程内刷新表
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.checkDetailTV reloadData];
                
                //若没有数据显示tipsLabel
                if (_dataArray.count > 0)
                {
                    _tipsLab.hidden = YES;
                    _checkDetailTV.hidden = NO;
                    self.view.backgroundColor = [UIColor whiteColor];
                }
                else
                {
                    _tipsLab.hidden = NO;
                    _checkDetailTV.hidden = YES;
                }
            });
            
            
        }
        else
        {
            
            [self showToastMessage:userBSGetBarcodeDatailResult.message];
        }
        
        
    }];
    
    _checkDetailTV.tableFooterView = [UIView new];
    
    [self initNavegationBar];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ROW_HEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"DetailsTableViewCell";
    DetailsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier ];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"DetailsTableViewCell" owner:nil options:nil][0];
    }
    
    cell.model = _dataArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * header = [[UIView alloc]init];
    //header.backgroundColor = [UIColor whiteColor];
    
    UILabel *allPayLab = [[UILabel alloc] init];
    allPayLab.frame = CGRectMake(0, 0, kMainScreenWidth/2, 40);
    allPayLab.font = [UIFont systemFontOfSize:16.0f];
    allPayLab.textAlignment = NSTextAlignmentCenter;
    allPayLab.text =[NSString stringWithFormat:@"总收入：%@",_allPay];
    
    UILabel *mothPayLab = [[UILabel alloc] init];
    mothPayLab.frame = CGRectMake(kMainScreenWidth/2, 0, kMainScreenWidth/2, 40);
    mothPayLab.font = [UIFont systemFontOfSize:16.0f];
    allPayLab.textAlignment = NSTextAlignmentCenter;
    mothPayLab.text =[NSString stringWithFormat:@"本月收入：%@",_monthPay];
    
    if (_dataArray.count > 0) {
        [header addSubview:allPayLab];
        [header addSubview:mothPayLab];
    }

    return header;
}

//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return UITableViewCellEditingStyleDelete;
//}
//-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    IncomeDetails *obj = _dataArray[indexPath.row];
//    [self.dataArray removeObject:obj];
//    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//}

#pragma mark - 下拉刷新/上提加载
/**
 *  下拉刷新
 */
- (void)addheaderRefresh
{    self.checkDetailTV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    _refreshPage = 1;
    isHedaRefresh = YES;
    [self getDataWithPageNum:_refreshPage andRefreshView:_checkDetailTV.header];
    
    }];
}

/**
 *  上提加载
 */
- (void)addfooterRefresh
{
    self.checkDetailTV.footer = [ MJRefreshBackFooter footerWithRefreshingBlock:^{
        _refreshPage +=1;
        
        [self getDataWithPageNum:_refreshPage andRefreshView:_checkDetailTV.footer];
        NSLog(@"加载第%d=页面数据",_refreshPage);
        
    }];
}

/**
 *  获取数据
 *
 *  @param page        请求数据页码，若大于1则为上提加载
 *  @param refreshView 刷新控件，若为nil,展示progressview
 */
- (void)getDataWithPageNum:(int)page andRefreshView:(MJRefreshComponent *)refreshView
{
    
    UserBSGetBarcodeDatail *userBSGetBarcodeDatail = [[UserBSGetBarcodeDatail alloc] init];
    userBSGetBarcodeDatail.page = [NSString stringWithFormat:@"%d",_refreshPage];
    
    if (!refreshView)
    {
        [self showProgressView];
    }
    [self runService:userBSGetBarcodeDatail andComplete:^(EACService *service) {
        //结束加载
        if(!refreshView)
        {
            [self hideProgressView];
        }
        else
        {
            [refreshView endRefreshing];
        }
    } andSuccess:^(EACService *service, id o) {
        //获取数据
        UserBSGetBarcodeDatailResult *userBSGetBarcodeDatailResult = o;
        //初始化界面
        _allPay = userBSGetBarcodeDatailResult.allpay;
        _monthPay = userBSGetBarcodeDatailResult.monthpay;
        
        if (userBSGetBarcodeDatailResult.isSucess)
        {
            NSArray* detailsArray = userBSGetBarcodeDatailResult.data;

            if (isHedaRefresh)
            {
                isHedaRefresh = NO;
                [self.dataArray removeAllObjects];
            }
            
            [  detailsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                BarcodeDetail *details = [[BarcodeDetail alloc] initWithclassName:obj[@"ticket_name"] classNum:obj[@"student_name"] andclassTime:obj[@"time"]];
                
                [self.dataArray addObject:details];
            
            }];
            
            //主线程内刷新表
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.checkDetailTV reloadData];
                //若没有数据显示tipsLabel
                if (_dataArray.count > 0)
                {
                    _tipsLab.hidden = YES;
                    _checkDetailTV.hidden = NO;
                    self.view.backgroundColor = [UIColor whiteColor];
                }
                else
                {
                    _tipsLab.hidden = NO;
                    _checkDetailTV.hidden = YES;
                }
                
            });

        }
        else
        {
            NSLog(@"~~~~~~~%@",userBSGetBarcodeDatailResult.message);
            [self showToastMessage:userBSGetBarcodeDatailResult.message];
        }
        
        
    }];
}



#pragma mark - NavegationBar
- (void)initNavegationBar
{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    backBtn.bounds = CGRectMake(0, 0, 15, 20);
    [backBtn addTarget:self action:@selector(onBackButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setBackgroundImage:[UIImage imageNamed:NAVIGATION_BACKARROW_IMAGE] forState:UIControlStateNormal];
    
    UIBarButtonItem *backBarBtn = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backBarBtn;
}

- (void)onBackButtonClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
